package com.qf.mvc01.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/download")
public class DownloadController {

    @Value("${fadd}")
    private String filepath;

    @RequestMapping("/test1")
    public void test1(String name, HttpServletResponse response) throws IOException {

        //1.根据传入文件名找到要下载的文件
        String finaFilePath = filepath + name;
        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+name);
        //把文件写入响应体中
        IOUtils.copy(new FileInputStream(finaFilePath),response.getOutputStream());

    }

@RequestMapping("/test2")
    public void test2(String name, HttpServletResponse response, HttpServletRequest request) throws IOException{
        //获取文件存放的路径
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/img");
        String fname = realPath + File.separator + name;
        response.setHeader("content-disposition","attachment;filename="+name);
        IOUtils.copy(new FileInputStream(fname),response.getOutputStream());
    }


}
